
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Region;
import com.cmc.dao.RegionDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class RegionDaoHibernate extends BaseDaoHibernate implements RegionDao {

    /**
     * @see com.cmc.dao.RegionDao#getRegions(com.cmc.model.Region)
     */
    public List getRegions(final Region region) {
        //return getHibernateTemplate().find("from Region");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (region == null) {
            return getHibernateTemplate().find("from Region");
        } else {
            // filter on properties set in the region
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(region).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Region.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.RegionDao#getRegion(Long id)
     */
    public Region getRegion(final Long id) {
        Region region = (Region) getHibernateTemplate().get(Region.class, id);
        if (region == null) {
            log.warn("uh oh, region with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Region.class, id);
        }

        return region;
    }

    /**
     * @see com.cmc.dao.RegionDao#saveRegion(Region region)
     */    
    public void saveRegion(final Region region) {
        getHibernateTemplate().saveOrUpdate(region);
    }

    /**
     * @see com.cmc.dao.RegionDao#removeRegion(Long id)
     */
    public void removeRegion(final Long id) {
        getHibernateTemplate().delete(getRegion(id));
    }
}
